package com.hmdp.service.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * session实现发送验证码
     * @param phone
     * @param session
     * @return
     */
    @Override
    public Result sendCodeBySession(String phone, HttpSession session) {
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式不正确");
        }

        //生成验证码
        String code = RandomUtil.randomNumbers(6);

        //保存验证码到session
        session.setAttribute(phone, code);

        return Result.ok(code);
    }

    /**
     * 基于redis实现发送验证码
     * @param phone
     * @return
     */
    @Override
    public Result sendCodeByRedis(String phone) {
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式不正确");
        }
        //生成验证码
        String code = RandomUtil.randomNumbers(6);

        //保存验证码到redis
        stringRedisTemplate.opsForValue().set(phone, code, 5L, TimeUnit.MINUTES);

        return Result.ok(code);
    }


    /**
     * session实现登录
     * @param loginForm
     * @param session
     * @return
     */
    @Override
    public Result loginBySession(LoginFormDTO loginForm, HttpSession session) {
        //1、校验手机号有效性
        if (RegexUtils.isPhoneInvalid(loginForm.getPhone())) {
            return Result.fail("手机号格式不正确");
        }

        //2、校验验证码
        String sessionCode = session.getAttribute(loginForm.getPhone()).toString();
        if (!Objects.equals(loginForm.getCode(), sessionCode)) {
            return Result.fail("验证码错误");
        }

        //3、如为新用户，保存用户信息
        User user = this.getOne(new LambdaQueryWrapper<User>().eq(User::getPhone, loginForm.getPhone()));
        if (Objects.isNull(user)) {
            user = new User();
            user.setPhone(loginForm.getPhone());
            user.setNickName("用户" + RandomUtil.randomString(10));
            this.save(user);
        }

        //4、保存用户信息到session
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user, userDTO);
        session.setAttribute("user", userDTO);

        return Result.ok();
    }


    /**
     * 基于redis实现登录
     * @param loginForm
     * @return
     */
    @Override
    public Result loginByRedis(LoginFormDTO loginForm) {
        //1、校验手机号有效性
        if (RegexUtils.isPhoneInvalid(loginForm.getPhone())) {
            return Result.fail("手机号格式不正确");
        }

        //2、校验验证码
        String sessionCode = stringRedisTemplate.opsForValue().get(loginForm.getPhone());
        if (!Objects.equals(loginForm.getCode(), sessionCode)) {
            return Result.fail("验证码错误");
        }

        //3、如为新用户，保存用户信息
        User user = this.getOne(new LambdaQueryWrapper<User>().eq(User::getPhone, loginForm.getPhone()));
        if (Objects.isNull(user)) {
            user = new User();
            user.setPhone(loginForm.getPhone());
            user.setNickName("用户" + RandomUtil.randomString(10));
            this.save(user);
        }
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user, userDTO);

        //4、保存用户信息到redis
        String token = UUID.randomUUID().toString();
        stringRedisTemplate.opsForValue().set(token, JSONUtil.toJsonStr(userDTO), 30, TimeUnit.MINUTES);

        return Result.ok(token);
    }
}
